package training.ui;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.TitledBorder;

public class SwingCalc extends JFrame {
	private JTextField jtfNumberOne = new JTextField();
	private JTextField jtfNumberTwo = new JTextField();
	private JTextField jtfOutput = new JTextField();
	private JComboBox jcb = new JComboBox(new Object[] { "Add", "Sub",
			"Multiply", "Divide" });

	public SwingCalc() {

		JPanel p1 = new JPanel();

		p1.setLayout(new GridLayout(3, 2, 5, 5));
		p1.add(new JLabel("FirstNumber"));
		p1.add(jtfNumberOne);
		p1.add(new JLabel("SecondNumber"));
		p1.add(jtfNumberTwo);
		p1.add(new JLabel("Output"));
		p1.add(jtfOutput);
		p1.setBorder(new TitledBorder(
				"Enter two numbers and select the operation"));
		JPanel p2 = new JPanel(new BorderLayout());
		p2.add(new JTextField("Calculator"), BorderLayout.NORTH);
		p2.add(p1, BorderLayout.WEST);

		add(p2, BorderLayout.CENTER);

		p2.add(jcb, BorderLayout.EAST);

		// Register Listener
		jcb.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// doAction(jcb.getSelectedItem());
				int index = jcb.getSelectedIndex();
				double num1 = Double.parseDouble(jtfNumberOne.getText());
				double num2 = Double.parseDouble(jtfNumberTwo.getText());

				if (index == 0)
					jtfOutput.setText(String.format("%.2f", num1 + num2));
				else if (index == 1)
					jtfOutput.setText(String.format("%.2f", num1 - num2));
				else if (index == 2)
					jtfOutput.setText(String.format("%.2f", num1 * num2));
				else if (index == 3)
					jtfOutput.setText(String.format("%.2f", num1 / num2));

			}

		});

	}

	public static void main(String[] args) {
		SwingCalc frame = new SwingCalc();
		frame.pack();
		frame.setTitle("Calculator");
		frame.setSize(300, 150);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}

}
